package com.tongzhan.service;

import com.tongzhan.base.BaseCriteria;
import com.tongzhan.base.BaseShareService;
import com.tongzhan.entity.MarkPrompt;
import com.tongzhan.entity.User;
import com.tongzhan.entity.qiaotai.Policy;
import com.tongzhan.utils.ThreadLocalUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author htmic
 * @date 2020/7/31
 */
@Service
public class PolicyService extends BaseShareService {

    /**
     * 列表
     * @param page
     * @param size
     * @return
     */
    public Page<Policy> getList(Integer page, Integer size) {
        Query query = new Query(BaseCriteria.where("is_del").is(0).and("type").is(2));
        PageRequest of = PageRequest.of(page, size, Sort.Direction.DESC, "addTime");
        if (ThreadLocalUtil.getThreadLocal().getDutiesCode().equals(ThreadLocalUtil.STREET_CODE)) {
            query.addCriteria(BaseCriteria.where("streetCode").like(ThreadLocalUtil.getThreadLocal().getStreetCode()));
        }
        if (ThreadLocalUtil.getThreadLocal().getDutiesCode().equals(ThreadLocalUtil.VILLAGE_CODE)) {
            query.addCriteria(BaseCriteria.where("villageCode").like(ThreadLocalUtil.getThreadLocal().getVillageCode()));
        }
        Page<Policy> all = policyRepository.findPage(query, of);
        return all;
    }

    /**
     * 新增侨资企业
     * @param entity
     * @return
     */
    public long add(Policy entity) {
        entity.setType(2);//侨台
        entity.setIs_del(0);
        entity.setTime(new Date());
        entity.setAddTime(new Date());
        User userById = findUserById(entity.getAddUserId());
        if(userById!=null){
            entity.setAddUserName(userById.getUserName());
        }
        entity.setStreetCode(ThreadLocalUtil.getThreadLocal().getStreetCode());
        entity.setVillageCode(ThreadLocalUtil.getThreadLocal().getVillageCode());
        long l = policyRepository.insertSelective(entity);
        if(l>0){
            //添加角标
            markPromptService.add(new MarkPrompt(2, entity.getId()));
            return  1;
        }
        return 0;
    }

    /**
     * 获取详情
     * @param id
     * @return
     */
    public Policy getDetail(String id,String userId) {
        Policy vo = policyRepository.findByPrimaryKey(id);
        //标记已读
        markPromptService.read(id,userId);
        return vo;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public long delPolicy(String id) {
        Policy entity = policyRepository.findByPrimaryKey(id);
        if(entity!=null){
            entity.setIs_del(1);
            long l = policyRepository.updateByPrimaryKeySelective(entity);
            if(l>0){
                return 1;
            }
        }
        return 0;
    }
}
